import {Injectable} from '@angular/core';
import {
    ActionSheetController,
    AlertController,
    IonRouterOutlet,
    LoadingController,
    MenuController,
    ModalController,
    NavController,
    Platform,
    PopoverController,
    ToastController,
    PickerController,
} from '@ionic/angular';
import {NativeService} from './native.service';
import {ActivatedRoute, Router} from '@angular/router';
import {AppMinimize} from '@ionic-native/app-minimize/ngx';
//import {StorageService} from './storage.service';

@Injectable({
    providedIn: 'root'
})
export class BackButtonService {

    private backButtonPressed:boolean = false;
    private currentUrl:string = '';
    private search:any;
    private rootIonRouterOutlet: IonRouterOutlet;

    constructor(
        private modalCtrl: ModalController,
        private menuCtrl: MenuController,
        private alertCtrl: AlertController,
        private toastCtrl: ToastController,
        private popOverCtrl: PopoverController,
        private actionSheetCtrl: ActionSheetController,
        private nativeService: NativeService,
        private activeRoute: ActivatedRoute,
        private loadingCtrl: LoadingController,
        private platform: Platform,
        private router: Router,
        private nav: NavController,
        private appMinimize: AppMinimize,
        private ac: ActivatedRoute,
        // private storage: StorageService,
        private loadingController: LoadingController,
        private pickerCtrl: PickerController
        ){
        //
    }

    public async registerBackButton(rootIonRouterOutlet: IonRouterOutlet) {
        this.rootIonRouterOutlet = rootIonRouterOutlet;
        this.platform.backButton.subscribeWithPriority(999, async () => {
            if (!this.backButtonPressed) {
                this.backButtonPressed = true;
                setTimeout(() => {
                    this.backButtonPressed = false;
                }, 800);
                await this.handleBackButtonPressed();
            }
        });
        // @ts-ignore
        this.rootIonRouterOutlet.stackCtrl.endBackTransition = (shouldBack: boolean) => {
            this.handleSwipeBackTriggered(shouldBack);
        };
    }

    public async preventModalSwipeBack() {
        this.rootIonRouterOutlet.swipeGesture = false;
        return true;
    }

    public async resumeModalSwipeBack() {
        this.rootIonRouterOutlet.swipeGesture = true;
        return true;
    }

    private async handleSwipeBackTriggered(shouldBack: boolean) {
        if (shouldBack) {
            console.log('测试滑动')
            this.currentUrl = location.pathname;
            if (this.currentUrl.startsWith('/evaluate-flow')) {
                return this.nav.navigateBack('/house-list', {animated: false});
            }
            if (this.currentUrl.startsWith('/house-list')) {
                return this.nav.navigateBack('/home', {animated: false});
            }
            if (this.currentUrl.startsWith('/process-flow')) {
                return this.nav.navigateBack('/home', {animated: false});
            }
            // @ts-ignore
            this.rootIonRouterOutlet.stackCtrl.skipTransition = true;
            this.nav.pop();
        } else {
            // @ts-ignore
            this.cleanup(this.rootIonRouterOutlet.stackCtrl.activeView,
                // @ts-ignore
                this.rootIonRouterOutlet.stackCtrl.views,
                // @ts-ignore
                this.rootIonRouterOutlet.stackCtrl.views,
                // @ts-ignore
                this.rootIonRouterOutlet.stackCtrl.location);
        }
    }

    /**
     * @Desc 重写ionic已经定义的backButton
     * @returns 
     */
    private async handleBackButtonPressed() {
        
        this.currentUrl = location.pathname;
        this.search = location.search;
        
        let num = '';
        if (this.search.includes('Rank=comprehensiveRanking') == true){
            num = 'flag';
        } else {
            num = '';
        }
        if (this.nativeService.isAndroid()) {
            // const flag = await this.storage.read('preview-picture');
            // if (flag) {
            //     console.log('flag' + flag);
            //     await this.storage.remove('preview-picture');
            //     return await this.modalCtrl.dismiss(true);
            // }
            const load = await this.loadingController.getTop();
            if (load) {
                load.dismiss();
                return ;
            }
            const modal = await this.modalCtrl.getTop();
            if (modal) {
                modal.dismiss();
                return ;
            }
            const picker = await this.pickerCtrl.getTop();
            if (picker) {
                await picker.dismiss();
                return;
            }

            if(this.currentUrl.startsWith("/home")){
                return this.nav.navigateBack('/login', {animated: false});
            }


            //在这之后的大部分代码要删除
            if (this.currentUrl.startsWith('/verification-details')){
                return this.nav.navigateBack('/to-be-verified', {animated: false});
            }
            if (this.currentUrl.startsWith('/process-flow')) {
                return this.nav.navigateBack('/home', {animated: false});
            }
            if (this.currentUrl.startsWith('/to-be-verified')){
                return this.nav.navigateBack('/verification', {animated: false});
            }
           
            if (this.currentUrl.startsWith('/product-name')
                || this.currentUrl.startsWith('/borrower-information')
                || this.currentUrl.startsWith('/house-property')
                || this.currentUrl.startsWith('/property-ownership-certificate')
                || this.currentUrl.startsWith('/evaluation')
                || this.currentUrl.startsWith('/evaluation-inquiry')
                || this.currentUrl.startsWith('/main-borrower')
                || this.currentUrl.startsWith('/property-coowner')
                || this.currentUrl.startsWith('/property-certificate')
                || this.currentUrl.startsWith('/risk-management')
                || (this.currentUrl.startsWith('/major-borrower') && num)
                || (this.currentUrl.startsWith('/main-manage') && num)
                || (this.currentUrl.startsWith('/property-owner') && num)
                || (this.currentUrl.startsWith('/borrow-owner') && num)
                || (this.currentUrl.startsWith('/property-information') && num)
                || (this.currentUrl.startsWith('/application') && num)
                || (this.currentUrl.startsWith('/interview-image-list') && num)
                || (this.currentUrl.startsWith('/survey-opinion') && num)
                || (this.currentUrl.startsWith('/authorized-limit')&& num)
                || (this.currentUrl.startsWith('/credit-contract') && num)
                || (this.currentUrl.startsWith('/guarantee-contract') && num)
                || (this.currentUrl.startsWith('/borrow-contract')&& num)
                || this.currentUrl.startsWith('/principal-borrower-information')
                || this.currentUrl.startsWith('/business-entity')
                || this.currentUrl.startsWith('/owner-house')
                || this.currentUrl.startsWith('/estate-information')
                || this.currentUrl.startsWith('/application-information')
                || this.currentUrl.startsWith('/image-list')
            ){
                console.log(this.currentUrl);
                return await this.backExit();
            }
            if (
                this.currentUrl.startsWith('/home') 
                || this.currentUrl.startsWith('/login')
                || this.currentUrl.startsWith('/verification') 
                || this.currentUrl.startsWith('/manager-home')) {
                console.log(this.currentUrl);
                return await this.showExit();
            }
            return this.nav.pop();
        }
    }

    /**
     * 是否关闭App的弹框?
     */
    private async showExit() {
        this.nativeService.showConfirm('要关闭APP吗?', '确定', () => {
            this.appMinimize.minimize();
        }, '取消');
    }


    /**
     * 信息未保存的弹框?
     */
    private async backExit() {
        this.nativeService.showConfirm('信息未保存，确认退出?', '确定', () => {
            this.nav.pop();
        }, '取消');
    }

    private cleanup(activeRoute, views, viewsSnapshot, location) {
        viewsSnapshot
            .filter((
                (view) => {
                    return !views.includes(view);
                }))
            .forEach((view) => {
                if (view) {
                    view.ref.destroy();
                    view.unlistenEvents();
                }
            });
        views.forEach((
            (view) => {
                const locationWithoutParams = location.path().split('?')[0];
                const locationWithoutFragment = locationWithoutParams.split('#')[0];
                if (view !== activeRoute && view.url !== locationWithoutFragment) {
                    const element = view.element;
                    element.setAttribute('aria-hidden', 'true');
                    element.classList.add('ion-page-hidden');
                    view.ref.changeDetectorRef.detach();
                }
            }));
    }
}
